<template>
  <div>
    <Modal
      class="modal-switch"
      title="贷超开关"
      footer-hide
      :value="value"
      :mask-closable="false"
      @on-cancel="handleModalCancel">
      
      <div class="modal-switch-inner">
        <label>贷超页面展示开关：</label>
        <i-switch
          class="iv-switch"
          :loading="sLoading"
          v-model="sValue"
          @on-change="handleSwitchChange"
          size="large">
          <span slot="open">开启</span>
          <span slot="close">关闭</span>
        </i-switch>
      </div>
    </Modal>
  </div>
</template>

<script>
  export default {
    name: 'switchComponent',
    props: {
      value: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        sLoading: true,
        sValue: false
      }
    },
    watch: {
      value(newVal) {
        if (newVal) {
          this.getItemConfig();
        }
      }
    },
    methods: {
      // 获取贷超的状态
      getItemConfig() {
        this.sLoading = true;
        this.$http.get('/helsinki/admin/config/item?key=sln:turku:db:showLoanMarket&field=guanwang&valueType=hash')
        .then(({ data: { errcode, info, data } }) => {
          if (errcode == 0) {
            this.sValue = data == '1';
          }
          this.sLoading = false;
        }, error => {});
      },
      // 弹窗 cancel
      handleModalCancel() {
        this.$emit('input', false);
      },
      beforeChange(value) {
        return new Promise((resolve) => {
          setTimeout(() => {
            resolve(value);
          }, 0);
        })
      },
      // switch change event
      handleSwitchChange(status) {
        const process = this.beforeChange(status);
        process && process.then((res) => {
          this.sValue = !res;
          this.$Modal.confirm({
          title: `确认${status ? '打开' : '关闭'}贷超开关`,
          loading: true,
          closable: true,
          onOk: () => {
            this.sLoading = true;
            this.$http.post('/helsinki/admin/config/update', {
              key: 'sln:turku:db:showLoanMarket',
              field: 'guanwang',
              value: res ? '1' : '0',
              valueType: 'hash'
            }).then(({ data: { errcode, info, data } }) => {
              if (errcode == 0) {
                this.$Message.success(`${res ? '已开启贷超开关' : '已关闭贷超开关'}`);
                this.getItemConfig();
              }
              this.sLoading = false;
              this.$Modal.remove();
            }, error => {});
          }
        });
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
  .modal-switch {
    .modal-switch-inner {
      padding: 24px 0;
      font-size: 13px;

      label {
        margin-right: 30px;
        display: inline-block;
        vertical-align: middle;
      }
    }
  }
</style>
